package com.augurit.gzcgwsp.ljzyz.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.excelimportexport.util.ExcelUtil;
import com.augurit.gzcgwsp.excelimportexport.util.FileUtil;
import com.augurit.gzcgwsp.excelimportexport.util.GetFileName;
import com.augurit.gzcgwsp.jzfqwczz.common.entity.YwYnBusinfoHfqk;
import com.augurit.gzcgwsp.jzfqwczz.common.service.IYwYnBusinfoHfqkService;
import com.augurit.gzcgwsp.ljzyz.convert.YwYnBusinfoConvertor;
import com.augurit.gzcgwsp.ljzyz.dao.BusIccardManageDao;
import com.augurit.gzcgwsp.ljzyz.entity.YwYnBusinfo;
import com.augurit.gzcgwsp.ljzyz.service.IBusIccardManageService;
import com.augurit.gzcgwsp.ljzyz.service.IYwYnBusinfoService;
import com.augurit.gzcgwsp.ljzyz.web.form.YwYnBusinfoForm;
import com.augurit.gzcgwsp.webservice.IccardWebservice;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;

@Service
@Transactional
public class BusIccardManageServiceImpl implements IBusIccardManageService{

	@Autowired
	private BusIccardManageDao busIccardManageDao;
	@Autowired
	private IYwComQyxxService ywComQyxxService;
	@Autowired
	private IYwYnBusinfoService ywYnBusinfoService;
	@Autowired
	private IYwYnBusinfoHfqkService ywYnBusinfoHfqkService;
	
	@Override
	public Page<YwYnBusinfoForm> search(Page<YwYnBusinfoForm> page,
			List<PropertyFilter> filters) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Page<YwYnBusinfoForm> search(Page<YwYnBusinfoForm> page,
			YwYnBusinfoForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);	
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps from YwYnBusinfo ps , YwComQyxx qyxx where 1=1  and ps.qyid = qyxx.id ");
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			if(form.getQyid()!=null){
				hql.append(" and qyxx.id="+form.getQyid());
			}
			
			if(StringUtils.isNotBlank(form.getGsmc())){
				hql.append(" and qyxx.sqdw like '%"+form.getGsmc()+"%'");
			}
		    if (StringUtils.isNotBlank(form.getCphm())) {
		        hql.append(" and ps.cphm like '%" + form.getCphm() + "%'");
		    }
		}
		//排序
		hql.append(" order by clbh asc");
		// 执行分页查询操作
		busIccardManageDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<YwYnBusinfoForm> list = convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	/**
	 * 转换form
	 * @param ywYnBusinfoList
	 * @return
	 */
	public  List<YwYnBusinfoForm> convertVoListToFormList(List<YwYnBusinfo> ywYnBusinfoList) {
		if(ywYnBusinfoList != null && ywYnBusinfoList.size() > 0) {
			List<YwYnBusinfoForm> ywYnBusinfoFormList = new ArrayList();
			for(int i=0; i<ywYnBusinfoList.size(); i++) {
				YwYnBusinfoForm form=YwYnBusinfoConvertor.convertVoToForm(ywYnBusinfoList.get(i));
				if(StringUtils.isBlank(form.getGsmc())){
					Long qyId=form.getQyid();
					String sqdw=ywComQyxxService.get(qyId).getSqdw();
					form.setGsmc(sqdw);
				}
				if(StringUtils.isBlank(form.getYwtzs())){
					form.setYwtzs("无");
				}
				//查询准运证有效期
				String zyzyxq=ywYnBusinfoService.getZyzyxqByBusId(form.getId());
				if(StringUtils.isNotBlank(zyzyxq)){
					String[] dates=zyzyxq.split("~");
					try {
						
						form.setYxjsrq(DateUtilsEX.dateFormate(dates[1],"yyyy-MM-dd"));
						form.setYxksrq(DateUtilsEX.dateFormate(dates[0],"yyyy-MM-dd"));
					} catch (ParseException e) {
						
						e.printStackTrace();
					}
				
				}
				
				form.setZyzyxqStr(zyzyxq);
				YwYnBusinfoHfqk hfqk=ywYnBusinfoHfqkService.getNewHfqkByBusId(form.getId());
				if(hfqk!=null && StringUtils.isNotBlank(hfqk.getIssendcard())){
					if("已发卡".equals(hfqk.getIssendcard())){
						form.setPintsts("√");
					}
				}
				
				ywYnBusinfoFormList.add(form);
			}
			return ywYnBusinfoFormList;
		}
		return null;
	}
	
	/*
	 * 读卡(non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IBusIccardManageService#readBusInfo()
	 */
	@Override
	public YwYnBusinfoForm readBusInfo() {
		IccardWebservice.openDev(1);
		YwYnBusinfoForm form=null;
		try {
			form=IccardWebservice.readInfo();
			String cphm=form.getCphm();
			String clbh=form.getClbh();
			YwYnBusinfoForm forms=ywYnBusinfoService.getBusByNo(cphm,clbh);
			if(forms!=null){
				form.setId(forms.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//关闭串口
			IccardWebservice.closeDev();
		}
		return form;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IBusIccardManageService#delCard()
	 */
	@Override
	public boolean  delCard() {
		boolean flag=false;
		IccardWebservice.openDev(1);
		try {
			flag=IccardWebservice.delCard();
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally{
			IccardWebservice.closeDev();
		}
		
		return flag;
	}

	/*
	 * 修改有效期(non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IBusIccardManageService#updateCard(java.lang.Long)
	 */
	@Override
	public boolean updateCard(Long busId) {
		boolean flag=false;
		String yxsj=ywYnBusinfoService.getZyzyxqByBusId(busId);
		try {
			Date date=DateUtilsEX.dateFormate(yxsj, "yyyyMMdd");
			yxsj=DateUtilsEX.dateFormate(date, "yyyyMMdd");
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		IccardWebservice.openDev(1);
		try {
			IccardWebservice.updateCard(yxsj);
			flag=true;
		} catch (RuntimeException e) {
			e.printStackTrace();
		}finally{
			//关闭串口
			IccardWebservice.closeDev();
		}
		return false;
	}
	/*
	 * 写卡(non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IBusIccardManageService#sendIccard()
	 */
	@Override
	public boolean sendIccard(Long busId,LoginUserForm user) {
		boolean flag=false;
		String content="";
		YwYnBusinfoForm form=ywYnBusinfoService.get(busId);
		//组成方式：标识号、车牌号、公司名称、车架号、发动机号、有效日期
	    String yxrq=ywYnBusinfoService.getZyzyxqByBusId(busId);
	    String edateStr="";
	    String sdateStr="";
	    if(StringUtils.isNotBlank(yxrq)){
	    	String[] rqstr=yxrq.split("~");
	    	if(rqstr.length>1){
	    		String sdatestr=rqstr[0];
	    		String enddate=rqstr[1];
	    		Date sdate=DateUtilsEX.getStringToDate(sdatestr, "yyyy-MM-dd");
	    		sdateStr=DateUtilsEX.dateFormate(sdate, "yyyyMMdd");
	    		Date edate=DateUtilsEX.getStringToDate(enddate, "yyyy-MM-dd");
	    		edateStr=DateUtilsEX.dateFormate(edate, "yyyyMMdd");
	    	}else{
	    		sdateStr=DateUtilsEX.dateFormate(new Date(), "yyyyMMdd");
	    		edateStr=DateUtilsEX.dateFormate(new Date(), "yyyyMMdd");
	    	}
	    }else{
	    	sdateStr=DateUtilsEX.dateFormate(new Date(), "yyyyMMdd");
    		edateStr=DateUtilsEX.dateFormate(new Date(), "yyyyMMdd");
	    }
	    if(StringUtils.isBlank(form.getSqdw())){
	       Long qyid=form.getQyid();
	       YwComQyxxForm qy=ywComQyxxService.get(qyid);
	       String sqdw=qy.getSqdw();
	       form.setSqdw(sqdw);
	    }
		 content=form.getClbh()+";"+form.getCphm()+";"+form.getSqdw()+";"+form.getCjh()+";"+
		 		form.getFdjh()+";"+sdateStr+edateStr;
		 System.out.println("打卡的内容-------"+content);
		  flag=IccardWebservice.openDev(1);
		  if(flag){
			  flag=IccardWebservice.writeInfo(content);
			  IccardWebservice.closeDev();
		  }
		  if(flag){//如果发卡成功写入发卡人
			  YwYnBusinfoHfqk hfqk=ywYnBusinfoHfqkService.getNewHfqkByBusId(form.getId());
			  if(hfqk!=null){
				  hfqk.setPrintman(user.getUser().getUserName());
				  hfqk.setPrinttime(new Date());
				  hfqk.setIssendcard("已发卡");
				  this.ywYnBusinfoHfqkService.updateEntity(hfqk);
			  }
			
		  }
		return flag;
	}
	
	/*
	 * 打印日期
	 * @see com.augurit.gzcgwsp.ljzyz.service.IBusIccardManageService#printDate(com.augurit.gzcgwsp.ljzyz.web.form.YwYnBusinfoForm, java.lang.String, java.lang.String)
	 */
	@Override
	public String printDate(YwYnBusinfoForm form, String context, String inpath) {
		 inpath=inpath.replace("/", File.separator);
	        String tempOutPath="Templates/businfo/outfile";
	        String fileName = GetFileName.getFileName("xls");
	        tempOutPath=this.buildPath(tempOutPath, fileName);
	        String outfilepath=context+"/"+tempOutPath;
	        outfilepath=outfilepath.replace("/", File.separator);
	        String outdir=outfilepath.substring(0,outfilepath.lastIndexOf(File.separator));
	        File file=new File(outdir);
	        if(!file.exists()){
	            file.mkdirs();
	        }
	        try {
				FileUtil.delDir(outdir, fileName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        writerDateExcel(inpath,outfilepath,form);
	        return tempOutPath;
	}

	/*
	 * 打卡(non-Javadoc)
	 * @see com.augurit.gzcgwsp.ljzyz.service.IBusIccardManageService#writeData(com.augurit.gzcgwsp.ljzyz.web.form.YwYnBusinfoForm, java.lang.String, java.lang.String)
	 */
	@Override
	public String writeData(YwYnBusinfoForm form, String context, String inpath) {
		 inpath=inpath.replace("/", File.separator);
	        String tempOutPath="Templates/businfo/outfile";
	        String fileName = GetFileName.getFileName("xls");
	        tempOutPath=this.buildPath(tempOutPath, fileName);
	        String outfilepath=context+"/"+tempOutPath;
	        outfilepath=outfilepath.replace("/", File.separator);
	        String outdir=outfilepath.substring(0,outfilepath.lastIndexOf(File.separator));
	        File file=new File(outdir);
	        if(!file.exists()){
	            file.mkdirs();
	        }
	        try {
				FileUtil.delDir(outdir, fileName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			writerDataExcel(inpath,outfilepath,form);
	        return tempOutPath;
	}
	 /**
     * 复制日期写入数据
     * @param inpath
     * @param outfilepath
     * @param form
     */
    private void writerDateExcel(String inpath, String outfilepath,
    		YwYnBusinfoForm form) {
        WritableWorkbook wwb;
        try {
            wwb = ExcelUtil.createWorkbookByOld(inpath, outfilepath);
            WritableSheet wsOne = ExcelUtil.getWritableSheetByIndex(wwb, 0);
            copyDate(wsOne,form);
            wwb.write();
            wwb.close();
        } catch (Exception e) {
          e.printStackTrace();
        } 
    }
	
	   /**
     * 复制模版写入数据
     * @param inpath
     * @param outfilepath
     * @param form
     */
    private void writerDataExcel(String inpath, String outfilepath,
    		YwYnBusinfoForm form) {
        WritableWorkbook wwb;
        try {
            wwb = ExcelUtil.createWorkbookByOld(inpath, outfilepath);
            WritableSheet wsOne = ExcelUtil.getWritableSheetByIndex(wwb, 0);
            copyData(wsOne,form);
            wwb.write();
            wwb.close();
        } catch (Exception e) {
          e.printStackTrace();
        } 
    }
    
    /**
     * 写数据
     * @param wsOne
     * @param form
     */
    private void copyData(WritableSheet wsOne, YwYnBusinfoForm form) {
       
        try {
            WritableCellFormat wcf=ExcelUtil.createCellFormat("宋体", 20, Alignment.LEFT, VerticalAlignment.CENTRE,false);
            // ExcelUtil.modiStrCell2(wsOne, 4,14, form.getZsbh()==null?"":form.getZsbh(), wcf);//编号
           
            //wcf.setLocked(false);
            //wcf1.setLocked(false);
           // wcf2.setLocked(false);
                 
        } catch (Exception e) {
            e.printStackTrace();

        } 
        
    }
    /**
     * 写日期
     * @param wsOne
     * @param form
     */
    private void copyDate(WritableSheet wsOne, YwYnBusinfoForm form) {
       
        try {
            WritableCellFormat wcf=ExcelUtil.createCellFormat("宋体", 20, Alignment.LEFT, VerticalAlignment.CENTRE,false);
            // ExcelUtil.modiStrCell2(wsOne, 4,14, form.getZsbh()==null?"":form.getZsbh(), wcf);//编号
           

                 
        } catch (Exception e) {
            e.printStackTrace();

        } 
        
    }
    /**
     * 生成后面的文件路径加上年月
     * @param realpath 定义的目录
     * @param fileNamesuffix 文件后缀名
     * @return
     */
    private String buildPath(String realpath,String fileName){
        String dateDir = GetFileName.getDirector();
        return realpath+"/"+dateDir+"/"+fileName;
        
    }
	
	@Override
	public void delete(Long... ids) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public YwYnBusinfoForm get(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void save(YwYnBusinfoForm... forms) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void saveInfo(String gdjrzh, String qydj,Long busId) {
		YwYnBusinfoHfqk hfqk=ywYnBusinfoHfqkService.getNewHfqkByBusId(busId);
		if(hfqk!=null){
			hfqk.setGdjrzh(gdjrzh);
			this.ywYnBusinfoHfqkService.updateEntity(hfqk);
		}
		//保存企业等级
		YwYnBusinfoForm form=this.ywYnBusinfoService.get(busId);
		form.setQydj(qydj);
		this.ywYnBusinfoService.save(form);
		
	}





	



}
